package com.ysynzehao.db;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * niuzehao
 * 2018/12/7 10:59.
 */
@Aspect
@Component
@Slf4j
public class DataSourceSwitchInterceptor {

    @Around("@annotation(dataSourceName)")
    public Object proceed(ProceedingJoinPoint proceedingJoinPoint, DataSourceName dataSourceName) throws Throwable {
        try {
            String value = dataSourceName.value().name();
            if (StringUtils.isEmpty(value)) {
                value = DbContextHolder.DbType.MASTER.name();
            }
            log.info("set database :" + value);
            DbContextHolder.setDbType(value);
            Object result = proceedingJoinPoint.proceed();
            return result;
        } finally {
            DbContextHolder.clearDbType();
            log.info("restore database connection");
        }
    }
}
